package com.chf.events;

import com.chf.mods.FirstMod;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LightningBolt;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.Random;

/**
 * 订阅客户端事件
 *
 * @author niooooo
 */
@Mod.EventBusSubscriber(modid = FirstMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class ClientEvent {

    /**
     * 玩家进入世界时触发
     *
     * @param event {@link PlayerEvent.PlayerLoggedInEvent}
     */
    @SubscribeEvent
    public static void playerJoinWorld(PlayerEvent.PlayerLoggedInEvent event) {
        // 1、获取玩家信息
        Player player = event.getEntity();
        // 2、构建消息
        final String message = "欢迎来到我的世界，%s".formatted(player.getName().getString());
        // 3、发送消息
        player.displayClientMessage(Component.literal(message), true);
    }

    /**
     * 方块被破坏时触发
     *
     * @param event {@link BlockEvent.BreakEvent}
     */
    @SubscribeEvent
    public static void playerJoinWorld(BlockEvent.BreakEvent event) {
        Player player = event.getPlayer();
        final String message = "%s 破坏了方块".formatted(player.getName().getString());
        player.displayClientMessage(Component.literal(message), true);
    }

    /**
     * 生物受伤时触发
     *
     * @param event {@link LivingHurtEvent}
     */
    @SubscribeEvent
    public static void livingHurt(LivingHurtEvent event) {
        // 获取伤害的来源
        DamageSource source = event.getSource();
        // 获取伤害实体
        LivingEntity entity = event.getEntity();

        // 仅当玩家伤害其他生物时触发
        if (!(source.getEntity() instanceof Player)) {
            return;
        }

        Player player = (Player) source.getEntity();
        Level world = player.level();
        // 1、确保只在服务端执行
        if (world.isClientSide) {
            return;
        }
        // 2、检查伤害来源是否存在
        if (source.getEntity() == null) {
            return;
        }

        // 30% 概率触发特效
        Random random = new Random();
        LivingEntity attacker = (LivingEntity) event.getSource().getEntity();
        if (random.nextDouble() < 0.3) {
            // 3、获取攻击者位置
            BlockPos attackerPos = attacker.blockPosition();

            // 4、创建闪电实体
            LightningBolt lightning = new LightningBolt(
                    net.minecraft.world.entity.EntityType.LIGHTNING_BOLT,
                    world
            );

            // 5、设置闪电位置（在攻击者头顶稍高处）
            lightning.moveTo(
                    attackerPos.getX() + 0.5,
                    attackerPos.getY() + 1,
                    attackerPos.getZ() + 0.5
            );

            // 6、添加到世界
            world.addFreshEntity(lightning);

            // 7、给攻击者添加发光效果（10秒，便于追踪）
            attacker.addEffect(new MobEffectInstance(
                    MobEffects.GLOWING,
                    200,
                    0,
                    false,
                    // 显示粒子效果
                    true
            ));

            // 8、播放复仇音效（附魔成功音效）
            world.playSound(
                    null,
                    player.getX(), player.getY(), player.getZ(),
                    SoundEvents.ENCHANTMENT_TABLE_USE,
                    SoundSource.PLAYERS,
                    1.0F,
                    0.8F + random.nextFloat() * 0.4F
            );

            // 9、发送闪电复仇提示
            player.sendSystemMessage(Component.literal("⚡ 天降正义惩罚了你的敌人! ⚡"));
            player.displayClientMessage(Component.literal("⚡ 劈死了傻呗"), false);
        }
    }

    /**
     * 玩家捡起物品时触发
     *
     * @param event {@link EntityItemPickupEvent}
     */
    @SubscribeEvent
    public static void entityItemPickup(EntityItemPickupEvent event) {
        Player player = event.getEntity();
        // 获取拾起物品到背包的信息
        ItemStack pickedUp = event.getItem().getItem();

        // 当捡起泥土时触发特殊效果
        if (pickedUp.getItem() == Items.DIRT) {
            // 1、给玩家随机奖励
            ItemStack[] rewards = {
                    new ItemStack(Items.GOLD_INGOT),
                    new ItemStack(Items.DIAMOND),
                    new ItemStack(Items.COOKIE),
                    new ItemStack(Items.TNT)
            };
            ItemStack reward = rewards[player.getRandom().nextInt(rewards.length)];
            player.addItem(reward);

            // 2、触发烟花特效
            Level world = player.level();
            for (int i = 0; i < 5; i++) {
                world.addParticle(ParticleTypes.FIREWORK,
                        player.getX(), player.getY() + 1, player.getZ(),
                        (world.random.nextDouble() - 0.5) * 0.5,
                        world.random.nextDouble() * 0.5,
                        (world.random.nextDouble() - 0.5) * 0.5);
            }

            // 3、播放音效
            player.playSound(SoundEvents.ITEM_PICKUP, 1.0F, 1.5F);

            // 4、发送有趣消息
            player.sendSystemMessage(Component.literal("泥土里居然藏了宝物?!"));
        }
    }
}
